<template>
    <div>
        <el-col :span="16">
            <el-row :gutter="8">
                <el-col :span="6">
                    <!--如果登录为医生，此时显示已经进行过对话的在线用户-->
                    <el-card v-if="user.role===4" style="width: 100%; min-height: 200px; color: #333">
                        <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc"><p style="font-size: 20px;color: #00CB8E"><b>在线用户</b></p>
                            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
                        <div class="user-box"  v-for="user in users"
                             :key="user.username" @click="createChat(user.username,user.nick)">
                            <span>{{ user.nick }}</span>
                            <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
                               ></i>
                            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">聊天中...</span>
                        </div>
                    </el-card>
                    <!--如果登录为用户，此时显示相关科室的在线医生-->
                    <el-card  v-if="user.role===2" class="box-card" style="margin-top: 20px">
                        <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc"><p style="font-size: 20px;color: #00CB8E"><b>在线医生</b></p>
                            <span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
                        <div class="user-box" v-for="user in users" :key="user.username" @click="createChat(user.username,user.nick)">
                            <span>{{ user.nick }}</span>
                            <i class="el-icon-chat-dot-round" style="margin-left: 10px; font-size: 16px; cursor: pointer"
                               ></i>
                            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">聊天中...</span>
                        </div>
                    </el-card>
                    <!--如果登录用户为医生，此处显示病患的真实信息-->
                    <el-card  v-if="user.role===4" class="box-card" style="margin-top: 20px">
                        <div style="padding-left:10px;padding-bottom: 10px; border-bottom: 1px solid #ccc">
                            <p style="font-size: 20px;color: #00CB8E"><b>用户真实信息</b></p></div>
                        <div class="userInfoCard"
                              :key="user.username">
                            <p>姓名：{{ userInfo.nickName }}</p>
                            <p>年龄：{{ userInfo.age }}</p>
                            <p>性别：{{ userInfo.gender }}</p>
                            <p>体重：{{ userInfo.weight }}</p>
                            <p>过敏史：{{ userInfo.allergy }}</p>
                            <p>药物史：{{ userInfo.medicHistory }}</p>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="18">
                    <el-card style="width: 40vw; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
                        <div style="text-align: center; line-height: 50px; font:18px '微軟正黑體 Light';
                        margin-bottom: 20px;color: #00CB8E">
                            <b>四叶草医生问询</b>（{{ chatNick }}）
                        </div>
                        <el-divider></el-divider>
                        <div style="height: 350px; overflow:auto; " v-html="content"></div>
                        <div style="height: 200px">
            <textarea v-model="text" @keydown.enter="send" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; outline: none"></textarea>
                            <div style="text-align: right; padding-right: 10px">
                                <el-button type="primary" size="mini" @click="send">发送</el-button>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-col>
    </div>
</template>
<script>
// import request from "@/utils/request";
import BaseUrl from "@/http/BaseUrl";
import SimpleAxios from "@/http/SimpleAxios";
import TokenAxios from "@/http/TokenAxios";

let socket;

export default {
    name: "Im",
    data() {
        return {
            circleUrl: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
            user: {},
            isCollapse: false,
            users: [],
            chatUser: '',
            text: "",
            messages: [],
            content: '',
            onlineuser:[],
            chatNick:'',
            userInfo:[],//医生展示的用户真实信息
            nowAvatar:'',
            remoteAvatar:''
        }
    },
    created() {
        this.init();


    },
    methods: {
        // loadCurrentLoginInfo(){
        //     this.user=JSON.parse(localStorage.getItem('loginInfo'));
        // },
        send() {
            if (!this.chatUser) {
                this.$message({type: 'warning', message: "请选择聊天对象"})
                return;
            }
            if (!this.text) {
                this.$message({type: 'warning', message: "请输入内容"})
            } else {
                if (typeof (WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                } else {
                    console.log("您的浏览器支持WebSocket");

                    // 组装待发送的消息 json
                    // {"from": "zhang", "to": "admin", "text": "聊天文本"}
                    let message = {from: this.user.username, to: this.chatUser, text: this.text}
                    console.log("chatUser="+this.chatUser)

                    socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
                    this.messages.push({user: this.user.username, text: this.text})
                    // 构建消息内容，本人消息
                    this.createContent(null, this.user.username, this.text)
                    this.text = '';
                }
            }
        },
        createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
            let html

            // 当前用户消息
            if (nowUser) { // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
                html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
                    "  <div class=\"el-col el-col-22\" style=\"text-align: right; padding-right: 10px\">\n" +
                    "    <div class=\"tip left\">" + text + "</div>\n" +
                    "  </div>\n" +
                    "  <div class=\"el-col el-col-2\">\n" +
                    "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                    "    <img src=\"" + this.nowAvatar + "\" style=\"object-fit: cover;\">\n" +
                    "  </span>\n" +
                    "  </div>\n" +
                    "</div>";


            } else if (remoteUser) {   // remoteUser表示远程用户聊天消息，蓝色的气泡
                html = "<div class=\"el-row\" style=\"padding: 5px 0\">\n" +
                    "  <div class=\"el-col el-col-2\" style=\"text-align: right\">\n" +
                    "  <span class=\"el-avatar el-avatar--circle\" style=\"height: 40px; width: 40px; line-height: 40px;\">\n" +
                    "    <img src=\"" + this.remoteAvatar + "\" style=\"object-fit: cover;\">\n" +
                    "  </span>\n" +
                    "  </div>\n" +
                    "  <div class=\"el-col el-col-22\" style=\"text-align: left; padding-left: 10px\">\n" +
                    "    <div class=\"tip right\">" + text + "</div>\n" +
                    "  </div>\n" +
                    "</div>";
                // this.content += html;

            }
            this.content+=html;
            // console.log(html)

        },
        init() {
            //user：登录用户的信息
            this.user = localStorage.getItem("loginInfo") ? JSON.parse(localStorage.getItem("loginInfo")) : {}
            console.log(this.user)
            let username = this.user.username;

            //获取当前登陆用户的头像
            let url=BaseUrl.CHAT+'/chat/getAvatar/'+username;
            console.log("getAvatarUrl="+url);
            TokenAxios.post(url).then((response)=>{
                // if(response.data.state===20000){
                this.nowAvatar=response.data.data[0].avatar;
                console.log(this.nowAvatar)
            })

            // let remoteUrl=BaseUrl.CHAT+'/chat/getAvatar/'+this.users.username;

            let _this = this;
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                let department=new URLSearchParams(location.search).get("depId");
                console.log("department="+department)
                console.log("您的浏览器支持WebSocket");
                let socketUrl;
                socketUrl = "ws://192.168.88.130:29800/imserver/"+username;//传入登陆用户的用户名
                console.log(socketUrl);
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                // 开启一个websocket服务
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function () {
                    console.log("websocket已打开");
                };
                //  浏览器端收消息，获得从服务端发送过来的文本消息,包括在线医生
                socket.onmessage = function (msg) {
                    console.log("收到数据====" + msg.data)
                    let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
                    if(_this.user.role===4){//医生
                        if (data.doc) {  // 获取在线人员信息
                            var key = _this.user.username
                            var map1 = data.doc
                            var map = new Map();
                            Object.entries(map1).forEach(([key, value]) => {
                                map.set(key, value);
                            });
                            var res = map.get(key)
                            if(res){
                                _this.users = res.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里

                            }
                            //_this.users = data.doc.filter(user => user.username !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
                        } else {
                            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
                            //  // {"from": "zhang", "text": "hello"}
                            if (data.from === _this.chatUser) {
                                _this.messages.push(data)
                                // 构建消息内容
                                _this.createContent(data.from, null, data.text)
                            }
                        }
                    }else {
                        if (data.users) {  // 获取在线人员信息
                            let department=new URLSearchParams(location.search).get("depId");
                            console.log("department="+department)
                            let departId=parseInt(department)
                            _this.users = data.users.filter(user => user.username !== username&& user.department === departId)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
                        } else {
                            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
                            //  // {"from": "zhang", "text": "hello"}
                            if (data.from === _this.chatUser) {
                                _this.messages.push(data)
                                // 构建消息内容
                                _this.createContent(data.from, null, data.text)
                            }
                        }
                    }

                };
                //关闭事件
                socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function () {
                    console.log("websocket发生了错误");
                }
            }
        },
        //查询在线医生
        queryHistory(userName){
            if(this.user.role===4){
                this.content = ''
                var param = {
                    doc_name: this.user.username,//登录用户为医生的用户名
                    user_name: userName,//对方用户名：用户
                }
                let infoUrl=BaseUrl.POST_DOCTOR+'/doctor/info/list/'+userName;
                console.log(infoUrl)
                TokenAxios.post(infoUrl).then((response)=>{
                    this.userInfo=response.data.data;
                    console.log(this.userInfo)
                })

                var url = BaseUrl.CHAT + '/chat/queryHistory';
                console.log(url);
                SimpleAxios.post(url, param).then((response) => {
                    let jsonResult = response.data;
                    if (jsonResult.state == 20000) {
                        var res = jsonResult.data
                        if (res) {
                            for (let i = 0; i < res.length; i++) {//send_user_name
                                if (this.user.username === res[i].sendUserName) {
                                    this.createContent(null, this.user.username, res[i].sendText)
                                } else if (userName === res[i].sendUserName) {
                                    this.createContent(userName, null, res[i].sendText)
                                }
                            }
                        }
                    } else {
                        this.$alert(jsonResult.message, '错误', {
                            confirmButtonText: '确定',
                            callback: action => {
                            }
                        });
                    }
                })
            }else {
                this.content = ''
                var param = {
                    doc_name: userName,
                    user_name: this.user.username
                }
                var url = BaseUrl.CHAT + '/chat/queryHistory'
                SimpleAxios.post(url, param).then((response) => {
                    let jsonResult = response.data;
                    if (jsonResult.state == 20000) {
                        var res = jsonResult.data
                        if (res) {
                            for (let i = 0; i < res.length; i++) {//send_user_name
                                if (this.user.username === res[i].sendUserName) {
                                    this.createContent(null, this.user.username, res[i].sendText)
                                } else if (userName === res[i].sendUserName) {
                                    this.createContent(userName, null, res[i].sendText)
                                }
                            }
                        }
                    } else {
                        this.$alert(jsonResult.message, '错误', {
                            confirmButtonText: '确定',
                            callback: action => {
                            }
                        });
                    }
                })
            }
        },

        createChat(username,nick,avatar){
            this.chatNick = nick
            //获取远方用户的头像
            let url=BaseUrl.CHAT+'/chat/getAvatar/'+username;
            console.log("getAvatarUrl="+url);
            TokenAxios.post(url).then((response)=>{
                // if(response.data.state===20000){
                this.remoteAvatar=response.data.data[0].avatar;
                console.log("remoteAvatar="+response.data.data[0].avatar)
                // console.log(this.remoteAvatar)

                this.chatUser = username

                this.queryHistory(this.chatUser)
                console.log("chatUser="+this.chatUser)
            })

        }

    },
    mounted() {
        // this.loadCurrentLoginInfo();
    }
}
</script>
<style>
.tip {
    color: white;
    text-align: center;
    border-radius: 10px;
    font-family: sans-serif;
    padding: 10px;
    width:auto;
    display:inline-block !important;
    display:inline;
}
.right {
    background-color: deepskyblue;
}
.left {
    background-color: forestgreen;
}
.userInfoCard{
    padding: 10px 0 10px 10px;
}
.userInfoCard p{
    font: 15px "微軟正黑體 Light";
    margin-bottom: 5px;
    margin-top: 10px;
}
.user-box{
    margin-top: 10px;
    padding: 10px 0 10px 10px;
    background-color: white;
    color: #333333;
    /*border-top-right-radius: 10px;*/
    /*border-bottom-right-radius: 10px;*/
    border-radius: 10px;
}
.user-box:hover{
    background-color: #daf5ec;
    cursor: pointer;

}
</style>
